package com.tools.mytools.encrypt;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import android.util.Log;

class HashUtil {

	private static final String LOG_TAG =  "HashUtil";
	public static final String HASH_SPEC_MD5 = "MD5";
	public static final String HASH_SPEC_SHA256 = "SHA-256";

	public static String encrypt(String strSrc, String encName) {
		MessageDigest md = null;
		String strDes = null;

		if (strSrc == null) {
		        Log.e(LOG_TAG, "src is null");
			return null;
		}

		byte[] bt = strSrc.getBytes();
		try {
			if (encName == null || encName.equals("")) {
				Log.e(LOG_TAG, "encName is null");
				return null;
			}
			md = MessageDigest.getInstance(encName);
			md.update(bt);
			strDes = bytes2Hex(md.digest()); // to HexString
			if (strDes == null || strDes.length() == 0) {
				Log.e(LOG_TAG, "result is null");
			}
		} catch (NoSuchAlgorithmException e) {
            Log.e(LOG_TAG, "" + e);
			return null;
		}
		
		return strDes;
	}

	public static String bytes2Hex(byte[] bts) {
		String des = "";
		String tmp = null;
		for (int i = 0; i < bts.length; i++) {
			tmp = (Integer.toHexString(bts[i] & 0xFF));
			if (tmp.length() == 1) {
				des += "0";
			}
			des += tmp;
		}
		return des;
	}
}
